from django.views import View
from .models import Area
from django.http import JsonResponse
from utils.response_code import RETCODE
from django.core.cache import cache


class AreasView(View):
    # 获取省市区
    def get(self, request):
        # 获取参数
        area_id = request.GET.get("area_id")
        if not area_id:
            province_list = cache.get("province_list")
            if not province_list:
                try:
                    # 查询省级数据
                    province_model_list = Area.objects.filter(parent_id__isnull=True)
                    province_list = [{"id": item.id, "name": item.name} for item in province_model_list]
                    cache.set("province_list", province_list)
                except Exception as e:
                    return JsonResponse({"code": RETCODE.DBERR, "errmsg": "查询省份数据错误"})
            return JsonResponse({"code": RETCODE.OK, "errmsg": "ok", "province_list": province_list})
        else:
            sub_data = cache.get('sub_data' + area_id)
            if not sub_data:
                try:
                    # 根据id获取该id的完整数据
                    province = Area.objects.get(id=area_id)
                    city_model_list = province.subs.all()
                    print(city_model_list)
                    subs = [{'id': item.id, 'name': item.name} for item in city_model_list]
                    sub_data = {
                        "id": province.id,
                        "name": province.name,
                        "subs": subs
                    }
                    cache.set('sub_data' + area_id, sub_data)
                except Exception as e:
                    return JsonResponse({"code": RETCODE.DBERR, "errmsg": "查询市区数据错误"})
            return JsonResponse({"code": RETCODE.OK, "errmsg": "ok", "sub_data": sub_data})
